import React, { useEffect, useRef } from 'react';
import { Card } from 'antd';
import * as echarts from 'echarts';
import type { ApiClassificationStats } from '../../../services/apiStatistics';

interface ApiClassificationChartProps {
    data: ApiClassificationStats | null;
    loading?: boolean;
}

const ApiClassificationChart: React.FC<ApiClassificationChartProps> = ({ data, loading = false }) => {
    const chartRef = useRef<HTMLDivElement>(null);
    const chartInstance = useRef<echarts.ECharts | null>(null);

    useEffect(() => {
        if (!chartRef.current || loading || !data) return;

        // 初始化图表
        if (!chartInstance.current) {
            chartInstance.current = echarts.init(chartRef.current);
        }

        // 准备数据，确保data和distribution存在
        const chartData = (data?.distribution || []).map(item => ({
            value: item.count,
            name: item.displayName || item.classType,
            itemStyle: {
                color: getClassTypeColor(item.classType)
            }
        }));

        // 配置图表选项
        const option = {
            title: {
                text: 'API类型识别统计',
                left: 'center',
                top: '5%',
                textStyle: {
                    fontSize: 24,
                    fontWeight: 'bold',
                    color: '#333'
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: function(params: any) {
                    const percentage = params.percent;
                    return `${params.name}<br/>数量: ${params.value}个<br/>占比: ${percentage}%`;
                }
            },
            legend: {
                orient: 'horizontal',
                bottom: '8%',
                left: 'center',
                textStyle: {
                    fontSize: 21  // 增大图例字体
                }
            },
            series: [
                {
                    name: '类型分布',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    center: ['50%', '50%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: true,
                        position: 'outside',
                        formatter: function(params: any) {
                            return `${params.name}\n${params.value}个\n${params.percent}%`;
                        },
                        fontSize: 19,  // 增大标签字体
                        fontWeight: 'bold'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: 21,
                            fontWeight: 'bold'
                        },
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    },
                    labelLine: {
                        show: true,
                        length: 15,
                        length2: 25
                    },
                    data: chartData,
                    animationDelay: function (idx: number) {
                        return Math.random() * 200;
                    }
                }
            ]
        } as any;

        chartInstance.current.setOption(option);

        // 监听窗口大小变化
        const handleResize = () => {
            chartInstance.current?.resize();
        };
        window.addEventListener('resize', handleResize);

        return () => {
            window.removeEventListener('resize', handleResize);
        };
    }, [data, loading]);

    // 组件卸载时销毁图表
    useEffect(() => {
        return () => {
            if (chartInstance.current) {
                chartInstance.current.dispose();
                chartInstance.current = null;
            }
        };
    }, []);

    // 获取类类型对应的颜色
    const getClassTypeColor = (classType: string): string => {
        const colorMap: { [key: string]: string } = {
            'INTERFACE': '#1890ff',
            'IMPLEMENTATION_CLASS': '#52c41a',
            'REGULAR_CLASS': '#fadb14',
            'ABSTRACT_CLASS': '#fa8c16',
            'UNKNOWN': '#d4d4d4'
        };
        return colorMap[classType] || '#667eea';
    };

    return (
        <Card 
            size="small" 
            loading={loading}
            style={{ 
                height: '400px',
                borderRadius: '12px',
                boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
            }}
            bodyStyle={{ height: '100%', padding: '16px' }}
        >
            <div 
                ref={chartRef} 
                style={{ 
                    width: '100%', 
                    height: '100%'
                }}
            />
        </Card>
    );
};

export default ApiClassificationChart;